package com.dmg.config;

import com.alibaba.fastjson.JSONObject;
import com.dmg.dao.PeiZhiMapper;
import com.dmg.entity.PeiZhi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 自定义增强类
 */
@Component
@Slf4j
public class MyAware implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    private PeiZhiMapper peiZhiMapper;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("进入自定义增强类");
        this.applicationContext = applicationContext;
        //读取数据库所有的数据源 重新初始化
        List<PeiZhi> list = peiZhiMapper.getList();
        log.info("读取数据库的所有数据源:{}", JSONObject.toJSONString(list));
        //从ioc容器上下文中 获取自己定义数据源
        MyDataSource bean = applicationContext.getBean(MyDataSource.class);
        //把数据库的数据源添加到ioc容器中,并重新初始化新的数据源
        bean.addPeiZhiList(list);
    }
}
